package com.example.zy.car.view.camera;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.example.zy.car.R;
import com.example.zy.car.custom.Preview;
import com.example.zy.car.custom.ShowCustomDialog;
import com.example.zy.car.utils.FileUtils;
import com.example.zy.car.utils.MyUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by zy on 2016/4/7.
 */
public class CameraActivity extends Activity implements View.OnClickListener {
    private Preview mPreview;
    Camera mCamera;
    int numberOfCameras;
    int cameraCurrentlyLocked;
    int defaultCameraId;
    Dialog dialog;
    private ImageView photoImage,cancle_camera;
    private static  final int REQUESTCODE=110;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_camera);
        mPreview = (Preview) findViewById(R.id.sfv_camera);
        numberOfCameras = Camera.getNumberOfCameras();

        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            int orientation = cameraInfo.orientation;
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                defaultCameraId = i;
            }
        }
        initView();
    }

    private void initView() {

        photoImage = (ImageView) findViewById(R.id.iv_camera_take_photo);
        photoImage.setOnClickListener(this);
        cancle_camera= (ImageView) findViewById(R.id.imgv_camera_cancle);
        cancle_camera.setOnClickListener(this);

        /**
         * 旋转图标
         */
    }
    // 创建jpeg图片回调数据对象
    Camera.PictureCallback jpeg = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            new PictureTask().execute(data);
        }

    };

    class PictureTask extends AsyncTask<byte[], Integer, String> {

        @Override
        protected void onPreExecute() {
            dialog = ShowCustomDialog.getInstance().loadingDialog(
                    CameraActivity.this, "");
            dialog.show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(byte[]... params) {
            byte[] data = params[0];

            long time = System.currentTimeMillis();
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            String picPath = Environment
                    .getExternalStorageDirectory().getAbsolutePath() + "/test/" + time +".jpg";
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/");
            if(!file.exists()){
                file.mkdirs();
            }
            boolean b = FileUtils.writeFile(picPath, new ByteArrayInputStream(
                    data));
            if (b) {
                b = false;
                FileOutputStream outputStream = null;
                try {
//					boolean front = (cameraCurrentlyLocked == Camera.CameraInfo.CAMERA_FACING_FRONT);

                    int degrees = MyUtil.getDegrees(cameraCurrentlyLocked);
                    if(degrees !=-1){
                        bitmap = MyUtil.RotationBitmap(bitmap,degrees);
                    }
                    outputStream = new FileOutputStream(picPath);
                    b = bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    b = false;
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e1) {
                            outputStream = null;
                        }
                    }
                }
                if (b) {
                    return picPath;
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (dialog != null) {
                dialog.dismiss();
            }
            if (result != null) {
                Intent intent = new Intent(CameraActivity.this,PhotoShowActivity.class);
                intent.putExtra("PhotoPath", result);
                startActivityForResult(intent,REQUESTCODE);
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUESTCODE){
            if(data!=null){
               CameraActivity.this.setResult(1,data); 
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCamera = Camera.open();
        cameraCurrentlyLocked = defaultCameraId;
        mPreview.setCamera(mCamera);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mCamera != null) {
            mPreview.setCamera(null);
            mCamera.release();
            mCamera = null;
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_camera_take_photo:
                photoImage.setEnabled(false);
                try {
                    mCamera.takePicture(new Camera.ShutterCallback() {
                        public void onShutter() {
                        }
                    }, null, jpeg);
                } catch (Exception e) {
                    photoImage.setEnabled(true);
                }
                break;
            case R.id.imgv_camera_cancle:
                finish();
                break;
            default:
                break;
        }
    }
  
}

